package com.hmall.controller.back;

import com.hdmall.business.common.annotation.AuthRequired;
import com.hdmall.business.common.common.ServerResponse;

import com.hmall.mapper.*;

import com.hmall.model.*;

import com.hmall.service.CustomerManage;

import com.hmall.service.PlanManageService;
import com.hdmall.business.common.util.HttpClientUtil;
import com.hdmall.business.common.util.ReadExcel;

import com.hmall.vo.*;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;


import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

import javax.servlet.http.HttpServletRequest;


@RestController
@RequestMapping("/manage/customer")
@Api(value = "后台客户管理操作API", description = "后台客户管理类API说明")
public class CustomerManageController {
    private final
    SysCustomerMapper sysCustomerMapper;
    private final
    SysDeptCustomerMapper sysDeptCustomerMapper;
    private final
    MallDealerMapper mallDealerMapper;
    private final
    SysUserMapper sysUserMapper;
    private final
    SysDeptMapper sysDeptMapper;
    private final
    CustomerManage customerManage;
    private final
    PlanManageService planManageService;
    private final
    MallProductPlanMapper mallProductPlanMapper;
    private final
    SysCustomerCreditMapper sysCustomerCreditMapper;
    private final
    SysCustomerCreditLogMapper sysCustomerCreditLogMapper;
    private final
    SysCustomerCreditTransactionMapper sysCustomerCreditTransactionMapper;
    private final
    MallOrderItemMapper mallOrderItemMapper;
    private final
    MallOrderMapper mallOrderMapper;
    private final
    MallPaymentUnpayMapper mallPaymentUnpayMapper;
    private final
    MallOrderFufillmentParentMapper mallOrderFufillmentParentMapper;
    private final
    SysCustomerKefuMapper sysCustomerKefuMapper;

    @Autowired
    public CustomerManageController(SysCustomerMapper sysCustomerMapper, SysDeptCustomerMapper sysDeptCustomerMapper, MallDealerMapper mallDealerMapper, SysCustomerCreditLogMapper sysCustomerCreditLogMapper, SysUserMapper sysUserMapper, SysDeptMapper sysDeptMapper, MallOrderFufillmentParentMapper mallOrderFufillmentParentMapper, MallOrderItemMapper mallOrderItemMapper, CustomerManage customerManage, PlanManageService planManageService, MallPaymentUnpayMapper mallPaymentUnpayMapper, MallOrderMapper mallOrderMapper, MallProductPlanMapper mallProductPlanMapper, SysCustomerCreditTransactionMapper sysCustomerCreditTransactionMapper, SysCustomerKefuMapper sysCustomerKefuMapper, SysCustomerCreditMapper sysCustomerCreditMapper) {
        this.sysCustomerMapper = sysCustomerMapper;
        this.sysDeptCustomerMapper = sysDeptCustomerMapper;
        this.mallDealerMapper = mallDealerMapper;
        this.sysCustomerCreditLogMapper = sysCustomerCreditLogMapper;
        this.sysUserMapper = sysUserMapper;
        this.sysDeptMapper = sysDeptMapper;
        this.mallOrderFufillmentParentMapper = mallOrderFufillmentParentMapper;
        this.mallOrderItemMapper = mallOrderItemMapper;
        this.customerManage = customerManage;
        this.planManageService = planManageService;
        this.mallPaymentUnpayMapper = mallPaymentUnpayMapper;
        this.mallOrderMapper = mallOrderMapper;
        this.mallProductPlanMapper = mallProductPlanMapper;
        this.sysCustomerCreditTransactionMapper = sysCustomerCreditTransactionMapper;
        this.sysCustomerKefuMapper = sysCustomerKefuMapper;
        this.sysCustomerCreditMapper = sysCustomerCreditMapper;
    }

    @AuthRequired
    @GetMapping("GetCustomerList")
    @ApiOperation(value = "获取办事处客户列表")
    public ServerResponse<List<CustomerWithUser>> GetCustomerList(Integer dept_id) {
        List<SysCustomer> list = sysCustomerMapper.selectByDeptId(dept_id);
        List<CustomerWithUser> result = new ArrayList<>();

        method1(list, result);

        return ServerResponse.createBySuccess(result);
    }

    private void method1(List<SysCustomer> list, List<CustomerWithUser> result) {
        for (SysCustomer aList : list) {
            Integer dept_id2 = sysDeptCustomerMapper.selectByCustomerId(aList.getCustomerId());
            Integer salesman_id = aList.getSalesmanId();
            SysUser sysUser = sysUserMapper.selectByPrimaryKey(salesman_id);
            String salesmanName = "";
            if (sysUser != null) {
                salesmanName = sysUser.getRealName();
            }
            List<SysUser> list2 = sysUserMapper.selectByDeptId(dept_id2);
            CustomerWithUser customerWithUser = new CustomerWithUser();
            customerWithUser.setBankName(aList.getBankName());
            customerWithUser.setBankNumber(aList.getBankNumber());
            customerWithUser.setBusAddress(aList.getBusAddress());
            customerWithUser.setBusName(aList.getBusName());
            customerWithUser.setBusPersonId(aList.getBusPersonId());
            customerWithUser.setBusPersonName(aList.getBusPersonName());
            customerWithUser.setBusiness(aList.getBusiness());
            customerWithUser.setCaptial(aList.getCaptial());
            customerWithUser.setCustomerId(aList.getCustomerId());
            customerWithUser.setInvoiceTitle(aList.getInvoiceTitle());
            customerWithUser.setInvoiceTitleAddr(aList
                    .getInvoiceTitleAddr());
            customerWithUser.setLinkmanName(aList.getLinkmanName());
            customerWithUser.setLinkmanTel(aList.getLinkmanTel());
            customerWithUser.setRegNum(aList.getRegNum());
            customerWithUser.setTaxNum(aList.getTaxNum());
            customerWithUser.setUserList(list2);
            customerWithUser.setValidPeriod(aList.getValidPeriod());
            customerWithUser.setSalesmanName(salesmanName);
            result.add(customerWithUser);
        }
    }

    @AuthRequired
    @GetMapping("SearchCustomer")
    @ApiOperation(value = "搜索客户")
    public ServerResponse<List<CustomerWithUser>> SearchCustomer(Integer dept_id, String search) {
        List<SysCustomer> list = sysCustomerMapper.selectByDeptIdAndSearch(dept_id,
                search);
        List<CustomerWithUser> result = new ArrayList<>();

        method1(list, result);

        return ServerResponse.createBySuccess(result);
    }

    @AuthRequired
    @GetMapping("SearchMyCustomer")
    @ApiOperation(value = "搜索我的客户")
    public ServerResponse<List<CustomerWithUser>> SearchMyCustomer(Integer dept_id, String search,
                                                                   Integer user_id) {
        List<SysCustomer> list = sysCustomerMapper.selectByDeptIdAndSearchAndUserId(dept_id,
                search, user_id);
        List<CustomerWithUser> result = new ArrayList<>();

        method2(list, result);

        return ServerResponse.createBySuccess(result);
    }

    private void method2(List<SysCustomer> list, List<CustomerWithUser> result) {
        for (SysCustomer aList : list) {
            Integer dept_id2 = sysDeptCustomerMapper.selectByCustomerId(aList.getCustomerId());
            List<SysUser> list2 = sysUserMapper.selectByDeptId(dept_id2);
            Integer salesman_id = aList.getSalesmanId();
            SysUser sysUser = sysUserMapper.selectByPrimaryKey(salesman_id);
            String salesmanName = "";
            if (sysUser != null) {
                salesmanName = sysUser.getRealName();
            }
            CustomerWithUser customerWithUser = new CustomerWithUser();
            customerWithUser.setBankName(aList.getBankName());
            customerWithUser.setBankNumber(aList.getBankNumber());
            customerWithUser.setBusAddress(aList.getBusAddress());
            customerWithUser.setBusName(aList.getBusName());
            customerWithUser.setBusPersonId(aList.getBusPersonId());
            customerWithUser.setBusPersonName(aList.getBusPersonName());
            customerWithUser.setBusiness(aList.getBusiness());
            customerWithUser.setCaptial(aList.getCaptial());
            customerWithUser.setCustomerId(aList.getCustomerId());
            customerWithUser.setInvoiceTitle(aList.getInvoiceTitle());
            customerWithUser.setInvoiceTitleAddr(aList
                    .getInvoiceTitleAddr());
            customerWithUser.setLinkmanName(aList.getLinkmanName());
            customerWithUser.setLinkmanTel(aList.getLinkmanTel());
            customerWithUser.setRegNum(aList.getRegNum());
            customerWithUser.setTaxNum(aList.getTaxNum());
            customerWithUser.setUserList(list2);
            customerWithUser.setSalesmanName(salesmanName);
            customerWithUser.setValidPeriod(aList.getValidPeriod());
            result.add(customerWithUser);
        }
    }

    @AuthRequired
    @PostMapping("AddCustomer")
    @ApiOperation(value = "添加客户")
    public String AddCustomer(@RequestBody
                                      SysCustomerVo sysCustomerVo) throws Exception {
        SysUser sysUser = sysUserMapper.selectByUserName(sysCustomerVo.getLinkman_tel());
        if (sysUser != null) {
            return "手机号已注册";
        }
        String result = customerManage.addCustomer(sysCustomerVo);
        Integer customer_id = sysCustomerMapper.selectCustomerByName(sysCustomerVo.getBus_name());
        customerManage.addUser(sysCustomerVo.getLinkman_tel(), "e10adc3949ba59abbe56e057f20f883e", customer_id, sysCustomerVo.getLinkman_name(), sysCustomerVo.getAuth_url(), sysCustomerVo.getLicense_url(), sysCustomerVo.getTax_cert_url(), sysCustomerVo.getId_face_url(), sysCustomerVo.getId_back_url());
        return result;
    }

    @AuthRequired
    @PostMapping("SaveCustomer")
    @ApiOperation(value = "保存客户")
    public ServerResponse SaveCustomer(@RequestBody
                                               CustomerVo sysCustomerVo) {
        System.out.println(sysCustomerVo.toString());

        Integer dealer_id = mallDealerMapper.selectDealerId(sysCustomerVo.getDept_id());
        SysCustomer sysCustomer = sysCustomerMapper.selectByPrimaryKey(sysCustomerVo.getCustomer_id());

        if (sysCustomer == null) {
            return ServerResponse.createByErrorMessage("客户不存在");
        }

        sysCustomer.setBusName(sysCustomerVo.getBus_name());
        sysCustomer.setLinkmanName(sysCustomerVo.getLinkman_name());
        sysCustomer.setLinkmanTel(sysCustomerVo.getLinkman_tel());
        sysCustomer.setBusPersonName(sysCustomerVo.getBus_person_name());
        sysCustomer.setBusPersonId(sysCustomerVo.getBus_person_id());
        sysCustomer.setBusAddress(sysCustomerVo.getBus_address());
        sysCustomer.setCaptial(sysCustomerVo.getCaptial());
        sysCustomer.setValidPeriod(sysCustomerVo.getValid_period());
        sysCustomer.setBusiness(sysCustomerVo.getBusiness());
        sysCustomer.setRegNum(sysCustomerVo.getReg_num());
        sysCustomer.setInvoiceTitle(sysCustomerVo.getInvoice_title());
        sysCustomer.setInvoiceTitleAddr(sysCustomerVo.getInvoice_title_addr());
        sysCustomer.setTaxNum(sysCustomerVo.getTax_num());
        sysCustomer.setBankName(sysCustomerVo.getBank_name());
        sysCustomer.setBankNumber(sysCustomerVo.getBank_number());
        sysCustomer.setDealerId(dealer_id);
        sysCustomerMapper.updateByPrimaryKey(sysCustomer);

        Integer dept_id = sysDeptCustomerMapper.selectByCustomerId(sysCustomerVo.getCustomer_id());
        SysDept sysDept = sysDeptMapper.selectByPrimaryKey(dept_id);
        sysDept.setName(sysCustomerVo.getBus_name());
        sysDeptMapper.updateByPrimaryKey(sysDept);

        return ServerResponse.createBySuccess("保存成功");
    }

    //    @PostMapping("AddUser")
//    @ApiOperation(value = "添加用户绑定客户")
//    public ServerResponse AddUser(String username, String password,
//                                  Integer dept_id, Integer customer_id) {
//        Integer user_id = sysUserMapper.selectIdByUsername(username);
//        SysCustomer sysCustomer = sysCustomerMapper.selectByPrimaryKey(customer_id);
//
//
//        SysUserRole sysUserRole = sysUserRoleMapper.selectRole(user_id);
//        if (sysUserRole == null){
//            SysUserRole sysUserRole1 = new SysUserRole();
//            sysUserRole1.setRoleId(3);
//            sysUserRole1.setUserId(user_id);
//            sysUserRoleMapper.insert(sysUserRole1);
//        }else {
//            int status = 3;
//            sysUserRoleMapper.updateStatus(user_id, status);
//        }
//        SysUserTemp sysUserTemp = new SysUserTemp();
//        sysUserTemp.setUserId(user_id);
//        sysUserTemp.setStatus(3);
//        sysUserTemp.setLinkmanName(sysCustomer.getLinkmanName());
//        sysUserTemp.setCreateTime(new Date());
//        sysUserTemp.setOpinion("通过");
//        sysUserTemp.setType(9);
//        sysUserTempMapper.insert(sysUserTemp);
//
//        return customerManage.addUser(username,password,dept_id,customer_id);
//    }
    @AuthRequired
    @PostMapping("ImportCustomer")
    @ApiOperation(value = "导入客户")
    public ServerResponse<String> ImportCustomer(MultipartFile file, Integer dept_id,
                                                 HttpServletRequest request)
            throws Exception {
        System.out.println(file);
        System.out.println(dept_id);

        File tempFile;

        tempFile = ProductManageController.getFile(file, request, null);

        List userList = ReadExcel.readExcel(tempFile);
        StringBuilder temp = new StringBuilder();

        assert userList != null;
        for (int i = 0; i < userList.size(); i++) {
            String s = userList.get(i).toString();
            s = s.substring(1, s.length() - 1);
            s = s.replaceAll(" ", "");

            String[] result = s.split(",");
            SysCustomerVo sysCustomerVo = new SysCustomerVo();
            sysCustomerVo.setBus_name(result[0]);
            sysCustomerVo.setLinkman_name(result[1]);
            sysCustomerVo.setLinkman_tel(result[2]);
            sysCustomerVo.setBus_person_name(result[3]);
            sysCustomerVo.setBus_person_id(result[4]);
            sysCustomerVo.setBus_address(result[5]);
            sysCustomerVo.setCaptial(result[6]);
            sysCustomerVo.setValid_period(result[7]);
            sysCustomerVo.setBusiness(result[8]);
            sysCustomerVo.setReg_num(result[9]);
            sysCustomerVo.setInvoice_title(result[10]);
            sysCustomerVo.setInvoice_title_addr(result[11]);
            sysCustomerVo.setTax_num(result[12]);
            sysCustomerVo.setBank_name(result[13]);
            sysCustomerVo.setBank_number(result[14]);
            sysCustomerVo.setDept_id(dept_id);
            temp.append("第").append(i).append("条数据").append(":").append(customerManage.addCustomer(sysCustomerVo)).append(",");
        }

        return ServerResponse.createBySuccess(temp.toString());
    }

    @AuthRequired
    @GetMapping("getSalesManList")
    @ApiOperation(value = "获取业务员列表")
    public ServerResponse<List<SalesmanVo>> getSalesManList(Integer dept_id) {
        List<SalesmanVo> list = sysUserMapper.selectSalesMan(dept_id);

        return ServerResponse.createBySuccess(list);
    }

    @AuthRequired
    @GetMapping("getbindingSalesMan")
    @ApiOperation(value = "获取绑定的业务员")
    public ServerResponse<String> getbindingSalesMan(Integer customer_id) {
        String salesmanName = sysCustomerMapper.selectSalesManName(customer_id);

        return ServerResponse.createBySuccess(salesmanName);
    }

    @AuthRequired
    @GetMapping("bindingSalesMan")
    @ApiOperation(value = "绑定业务员")
    public ServerResponse bindingSalesMan(Integer customer_id,
                                          Integer salesman_id) {
        SysCustomer sysCustomer = sysCustomerMapper.selectByPrimaryKey(customer_id);

        if (sysCustomer == null) {
            return ServerResponse.createByErrorMessage("客户不存在");
        }

        sysCustomer.setSalesmanId(salesman_id);
        sysCustomerMapper.updateByPrimaryKey(sysCustomer);

        //判断该客户是否创建了计划
        //获得该客户最早注册的用户
        Integer user_id = sysCustomerMapper.selectCustomerUserId(customer_id);
        if (user_id == null) {
            return ServerResponse.createByErrorMessage("该客户下没有用户");
        }
        Date date = new Date();
        List<MallProductPlan> list = mallProductPlanMapper.checkPlan(user_id, date);
        if (list.size() == 0) {
            //创建今年十二个月的生成计划
            Calendar calendar = Calendar.getInstance();
            calendar.set(Calendar.DAY_OF_MONTH, 1);
            calendar.set(Calendar.HOUR_OF_DAY, 0);
            calendar.set(Calendar.MINUTE, 0);
            calendar.set(Calendar.SECOND, 0);
            for (int i = 1; i <= 12; i++) {
                calendar.set(Calendar.MONTH, i - 1);
                System.out.println(calendar.getTime().toLocaleString());
                planManageService.createPlan(customer_id, calendar.getTime());
            }
        } else {
            for (MallProductPlan mallProductPlan : list) {
                mallProductPlan.setSaleUserId(salesman_id);
                mallProductPlanMapper.updateByPrimaryKey(mallProductPlan);
            }
        }
        return ServerResponse.createBySuccess("绑定成功");
    }

    @AuthRequired
    @GetMapping("GetMyCustomer")
    @ApiOperation(value = "获取我的客户")
    public ServerResponse<List<CustomerWithUser>> GetMyCustomer(Integer dept_id, Integer user_id) {
        List<SysCustomer> list = sysCustomerMapper.selectByDeptIdAndUserId(dept_id,
                user_id);
        List<CustomerWithUser> result = new ArrayList<>();

        method2(list, result);

        return ServerResponse.createBySuccess(result);
    }

    @AuthRequired
    @GetMapping("getSalesManListByDealer")
    @ApiOperation(value = "通过dealer_id获取业务员列表")
    public ServerResponse<List<SalesmanVo>> getSalesManListByDealer(Integer dealer_id) {
        MallDealer mallDealer = mallDealerMapper.selectByPrimaryKey(dealer_id);
        List<SalesmanVo> list = sysUserMapper.selectSalesMan(mallDealer.getDeptId());

        return ServerResponse.createBySuccess(list);
    }

    @AuthRequired
    @GetMapping("getCustomerCreditList")
    @ApiOperation(value = "获得客户授信额度列表")
    public ServerResponse<List<CreditVo>> getCustomerCreditList(Integer dept_id, Integer customer_id) {
        List<CreditVo> list = sysCustomerCreditMapper.selectCreditList(dept_id, customer_id);
        return ServerResponse.createBySuccess(list);
    }

    @AuthRequired
    @PostMapping("editCredit")
    @ApiOperation(value = "编辑客户授信额度")
    public ServerResponse editCredit(Integer user_id, Integer customer_id, Integer lines, Integer accountPeriod, String effective_time) throws Exception {
//        MallPaymentUnpay mallPaymentUnpay = mallPaymentUnpayMapper.selectByCustomerId(customer_id);
//        if (mallPaymentUnpay!=null){
//            if (mallPaymentUnpay.getUnpayPayment().compareTo(new BigDecimal(0))==1){
//                return ServerResponse.createByErrorMessage("该客户有未付清欠款，不能修改");
//            }
//        }
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String roleName = sysUserMapper.selectRoleName(user_id);
        SysUser sysUser = sysUserMapper.selectByPrimaryKey(user_id);
        SysCustomer sysCustomer = sysCustomerMapper.selectByPrimaryKey(customer_id);
        SysCustomerCredit sysCustomerCredit = sysCustomerCreditMapper.selectByCustomerId(customer_id);
        if (sysCustomerCredit == null) {
            SysCustomerCredit sysCustomerCredit1 = new SysCustomerCredit();
            sysCustomerCredit1.setCustomerId(customer_id);
            sysCustomerCredit1.setQuota(0);
            sysCustomerCredit1.setAccountPeriod(0);
            sysCustomerCreditMapper.insert(sysCustomerCredit1);
            SysCustomerCredit sysCustomerCredit2 = sysCustomerCreditMapper.selectByCustomerId(customer_id);
            Integer sys_customer_credit_id;
            if (sysCustomerCredit2 == null) {
                return ServerResponse.createByErrorMessage("错误");
            } else {
                sys_customer_credit_id = sysCustomerCredit2.getSysCustomerCreditId();
            }
            SysCustomerCreditTransaction sysCustomerCreditTransaction = sysCustomerCreditTransactionMapper.selectByCustomerId(customer_id);
            method3(customer_id, lines, accountPeriod, effective_time, sdf, sysCustomerCreditTransaction);
//            sysCustomerCredit = sysCustomerCreditMapper.selectByCustomerId(customer_id);
            SysCustomerCreditLog sysCustomerCreditLog = new SysCustomerCreditLog();
            sysCustomerCreditLog.setSysCustomerCreditId(sys_customer_credit_id);
            String content = roleName + sysUser.getRealName() + "在" + (new Date()).toLocaleString() + "将客户:" + sysCustomer.getBusName() + "的额度" + "由" + "0" + "修改为" + lines + ",账期" + "由" + "0" + "修改为" + accountPeriod + ",执行时间为:" + sdf.parse(effective_time).toLocaleString();
            sysCustomerCreditLog.setContent(content);
            sysCustomerCreditLogMapper.insert(sysCustomerCreditLog);
        } else {
            String str1 = sysCustomerCredit.getQuota().toString();
            String str2 = sysCustomerCredit.getAccountPeriod().toString();
            SysCustomerCreditTransaction sysCustomerCreditTransaction = sysCustomerCreditTransactionMapper.selectByCustomerId(customer_id);
            method3(customer_id, lines, accountPeriod, effective_time, sdf, sysCustomerCreditTransaction);
            SysCustomerCreditLog sysCustomerCreditLog = new SysCustomerCreditLog();
            sysCustomerCreditLog.setSysCustomerCreditId(sysCustomerCredit.getSysCustomerCreditId());
            String content = roleName + sysUser.getRealName() + "在" + (new Date()).toLocaleString() + "将客户:" + sysCustomer.getBusName() + "的额度" + "由" + str1 + "修改为" + lines + ",账期" + "由" + str2 + "修改为" + accountPeriod + ",执行时间为:" + sdf.parse(effective_time).toLocaleString();
            sysCustomerCreditLog.setContent(content);
            sysCustomerCreditLogMapper.insert(sysCustomerCreditLog);
        }
        return ServerResponse.createBySuccess("编辑成功");
    }

    private void method3(Integer customer_id, Integer lines, Integer accountPeriod, String effective_time, SimpleDateFormat sdf, SysCustomerCreditTransaction sysCustomerCreditTransaction) throws ParseException {
        if (sysCustomerCreditTransaction != null) {
            sysCustomerCreditTransaction.setAccountPeriod(accountPeriod);
            sysCustomerCreditTransaction.setQuota(lines);
            sysCustomerCreditTransaction.setEffectiveTime(sdf.parse(effective_time));
            sysCustomerCreditTransaction.setStatus(0);
            sysCustomerCreditTransactionMapper.updateByPrimaryKey(sysCustomerCreditTransaction);
        } else {
            SysCustomerCreditTransaction sysCustomerCreditTransaction2 = new SysCustomerCreditTransaction();
            sysCustomerCreditTransaction2.setCustomerId(customer_id);
            sysCustomerCreditTransaction2.setAccountPeriod(accountPeriod);
            sysCustomerCreditTransaction2.setQuota(lines);
            sysCustomerCreditTransaction2.setEffectiveTime(sdf.parse(effective_time));
            sysCustomerCreditTransaction2.setStatus(0);
            sysCustomerCreditTransactionMapper.insert(sysCustomerCreditTransaction2);
        }
    }

    @AuthRequired
    @GetMapping("getCreditLog")
    @ApiOperation(value = "获得授信修改日志")
    public ServerResponse<List<SysCustomerCreditLog>> getCreditLog(Integer sysCustomerCreditId) {
        List<SysCustomerCreditLog> list = sysCustomerCreditLogMapper.selectLog(sysCustomerCreditId);
        return ServerResponse.createBySuccess(list);
    }

    @AuthRequired
    @GetMapping("findCredit")
    @ApiOperation(value = "获得用户授信信息")
    public ServerResponse findCredit(Integer item_id) {
        MallOrderItem mallOrderItem = mallOrderItemMapper.selectByPrimaryKey(item_id);
        if (mallOrderItem == null) {
            return ServerResponse.createByErrorMessage("item_id错误");
        }
        MallOrder mallOrder = mallOrderMapper.selectByOrderNo(mallOrderItem.getOrderNo());
        if (mallOrder == null) {
            return ServerResponse.createByErrorMessage("订单错误");
        }
        Integer customer_id = sysCustomerMapper.selectCustomerId(mallOrder.getUserId());
        SysCustomerCredit sysCustomerCredit = sysCustomerCreditMapper.selectByCustomerId(customer_id);
        return ServerResponse.createBySuccess(sysCustomerCredit);
    }

    @AuthRequired
    @GetMapping("checkCredit")
    @ApiOperation(value = "检测用户授信额度")
    public ServerResponse checkCredit(BigDecimal payment, String username) {
        SysUser sysUser = sysUserMapper.selectByUserName(username);
        Integer customer_id = sysCustomerMapper.selectCustomerId(sysUser.getUserId());
        SysCustomerCredit sysCustomerCredit = sysCustomerCreditMapper.selectByCustomerId(customer_id);
        Integer quota = 0;
        BigDecimal unpayment = new BigDecimal(0);
        if (sysCustomerCredit != null) {
            quota = sysCustomerCredit.getQuota();
        }
        MallPaymentUnpay mallPaymentUnpay = mallPaymentUnpayMapper.selectByCustomerId(customer_id);
        if (mallPaymentUnpay != null) {
            unpayment = mallPaymentUnpay.getUnpayPayment();
        }
        BigDecimal money = new BigDecimal(quota).subtract(unpayment);
        int a = money.compareTo(payment);
        if (a < 0) {
            return ServerResponse.createByErrorMessage("当前额度为" + money + "本次申请金额为" + payment + ",请注意");
        } else {
            return ServerResponse.createBySuccess("当前额度为" + money + "本次申请金额为" + payment + ",可以下单");
        }
    }

    @AuthRequired
    @GetMapping("checkAccountPeriod")
    @ApiOperation(value = "检查客户账期")
    public ServerResponse checkAccountPeriod(Integer item_id) {
        MallOrderItem mallOrderItem = mallOrderItemMapper.selectByPrimaryKey(item_id);
        if (mallOrderItem == null) {
            return ServerResponse.createByErrorMessage("item_id错误");
        }
        MallOrder mallOrder = mallOrderMapper.selectByOrderNo(mallOrderItem.getOrderNo());
        if (mallOrder == null) {
            return ServerResponse.createByErrorMessage("订单不存在");
        }
        Integer customer_id = sysCustomerMapper.selectCustomerId(mallOrder.getUserId());
        List<MallOrderFufillmentParent> list = mallOrderFufillmentParentMapper.selectByCustomerId2(customer_id);
        SysCustomerCredit sysCustomerCredit = sysCustomerCreditMapper.selectByCustomerId(customer_id);
        if (sysCustomerCredit == null || (sysCustomerCredit.getQuota() == 0 && sysCustomerCredit.getAccountPeriod() == 0)) {
            return ServerResponse.createBySuccess("该用户为现金用户");
        }
        if (list.size() == 0) {
            return ServerResponse.createBySuccess("该用户没有账期超时，可以发货");
        } else {
            String s = "该用户账期超时";
            return ServerResponse.createByErrorMessage(s);
        }
    }

    @AuthRequired
    @GetMapping("test")
    @ApiOperation(value = "sss")
    public ServerResponse<String> test() {
        Map<String, String> map = new HashMap<>();
        map.put("id", "55555");
        map.put("username", "55555");
        map.put("deal_way", "55555");
        map.put("address", "55555");
        map.put("remark", "55555");
        map.put("create_time", "55555");
        map.put("status", "55555");
        map.put("salesman_name", "55555");
        map.put("plan_no", "55555");
        map.put("opinion", "55555");
        map.put("productList", "55555");
        String s = HttpClientUtil.doPostWithParam("http://47.98.171.71:8081/hdfind/createPlan", map);
        return ServerResponse.createBySuccess(s);
    }

    @AuthRequired
    @GetMapping("getCustomerList")
    @ApiOperation(value = "获得未绑定客服客户列表")
    public ServerResponse<List<MyCustomerVo>> getCustomerList() {
        List<MyCustomerVo> list = sysCustomerMapper.getCustomerList();
        return ServerResponse.createBySuccess(list);
    }

    @AuthRequired
    @GetMapping("getCustomerKefuList")
    @ApiOperation(value = "获得客户客服绑定列表")
    public ServerResponse<List<CustomerKefuVo>> getCustomerKefuList(String query) {
        List<SysCustomer> list = sysCustomerMapper.selectByQuery(query);
        List<CustomerKefuVo> list2 = new ArrayList<>();
        for (SysCustomer aList : list) {
            CustomerKefuVo customerKefuVo = new CustomerKefuVo();
            customerKefuVo.setBus_name(aList.getBusName());
            customerKefuVo.setCustomer_id(aList.getCustomerId());
            List<CustomerKefuVo> list1 = sysCustomerKefuMapper.selectAllList(aList.getBusName());
            if (list1.size() == 0) {
                continue;
            } else {
                for (CustomerKefuVo aList1 : list1) {
                    if (customerKefuVo.getKefu_name() == null) {
                        customerKefuVo.setKefu_name(aList1.getKefu_name());
                    } else {
                        customerKefuVo.setKefu_name(customerKefuVo.getKefu_name() + "," + aList1.getKefu_name());
                    }
                }
            }
            list2.add(customerKefuVo);
        }
        return ServerResponse.createBySuccess(list2);
    }

    @AuthRequired
    @PostMapping("bindingKefu")
    @ApiOperation(value = "绑定客服")
    public ServerResponse<String> bindingKefu(Integer[] user_id, Integer customer_id) {
        sysCustomerKefuMapper.deleteByCustomerId(customer_id);
        for (Integer anUser_id : user_id) {
            SysCustomerKefu sysCustomerKefu = new SysCustomerKefu();
            sysCustomerKefu.setCustomerId(customer_id);
            sysCustomerKefu.setUserId(anUser_id);
            sysCustomerKefuMapper.insert(sysCustomerKefu);
        }
        return ServerResponse.createBySuccess("绑定成功");
    }
}
